package com.example.simin_manage.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.simin_manage.admim.dto.OrderStatisticsDTO;
import com.example.simin_manage.entity.OrderRecord;
import com.example.simin_manage.entity.PerformancePeriod;
import com.example.simin_manage.entity.SysDept;
import com.example.simin_manage.entity.SysUser;
import com.example.simin_manage.mapper.DeptMapper;
import com.example.simin_manage.mapper.OrderMapper;
import com.example.simin_manage.mapper.PerformancePeriodMapper;
import com.example.simin_manage.mapper.SysUserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: panpan
 * @time: 2025/9/21
 */
@Service
public class leaderService extends ServiceImpl<OrderMapper, OrderRecord> {

    @Resource
    private DeptMapper deptMapper;
    @Resource
    private SysUserMapper userMapper;
    @Resource
    private PerformancePeriodMapper periodMapper;

    public List<OrderStatisticsDTO> getOrderStatistics(Long leaderId, Long memberId,
                                                       LocalDate start, LocalDate end,
                                                       Long periodId) {
        // 如果没有 start/end，就用当前周期
        if (start == null || end == null) {
            PerformancePeriod period = (periodId != null)
                    ? periodMapper.selectById(periodId)
                    : periodMapper.selectOne(new QueryWrapper<PerformancePeriod>()
                    .eq("status", 1)); // 假设 status=1 表示当前周期

            if (period != null) {
                start = period.getStartDate();
                end = period.getEndDate();
            } else {
                start = LocalDate.now().minusDays(6);
                end = LocalDate.now();
            }
        }

        // 找到组长对应部门
        SysDept dept = deptMapper.selectOne(new QueryWrapper<SysDept>().eq("leader_id", leaderId));
        if (dept == null) {
            return Collections.emptyList();
        }

        // 获取部门下所有成员
        List<Long> userIds = userMapper.selectList(new QueryWrapper<SysUser>().eq("dept_id", dept.getId()))
                .stream()
                .map(SysUser::getId)
                .collect(Collectors.toList());

        if (userIds.isEmpty()) {
            return Collections.emptyList();
        }

        QueryWrapper<OrderRecord> wrapper = new QueryWrapper<>();
        wrapper.between("record_date", start, end);

        if (memberId != null) {
            wrapper.eq("user_id", memberId);
        } else {
            wrapper.in("user_id", userIds);
        }

        // ⚡ 这里区分逻辑：
        // 单人：只 group by 日期
        // 全组：group by 日期 + user_id
        if (memberId != null) {
            wrapper.select("DATE(record_date) AS date", "SUM(order_count) AS orderCount", "user_id")
                    .groupBy("DATE(record_date)", "user_id")
                    .orderByAsc("DATE(record_date)");
        } else {
            wrapper.select("DATE(record_date) AS date", "user_id", "SUM(order_count) AS orderCount")
                    .groupBy("DATE(record_date)", "user_id")
                    .orderByAsc("DATE(record_date)");
        }

        List<Map<String, Object>> maps = baseMapper.selectMaps(wrapper);

        return maps.stream()
                .map(m -> new OrderStatisticsDTO(
                        m.get("date").toString(),
                        Long.parseLong(m.get("user_id").toString()),
                        Integer.parseInt(m.get("orderCount").toString())
                ))
                .collect(Collectors.toList());
    }
}
